<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Phone extends Model
{
    protected $fillable = [
        'friendly_name', 'phone_number','locality', 'isoCountry', 'capabilities', 'status','phone_setting_id'
    ];

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function setting(){
        return $this->belongsTo(PhoneSetting::class,'phone_setting_id');
    }
    //同步TW和PL的电话号码
    public function updateSettingPhone($list, $setting_id=''){
        foreach($list as $v){
           $res = self::where('phone_number',$v)->count();
           if(!$res){
               self::insert([
                   'friendly_name'=>$v,
                   'phone_number'=>$v,
                   'phone_setting_id'=>$setting_id,
                   'created_at'=>Carbon::now()->toDateTimeString(),
                   'updated_at'=>Carbon::now()->toDateTimeString(),
               ]);
           }else{
               self::where('phone_number',$v)->update([
                   'phone_setting_id'=>$setting_id,
                   'updated_at'=>Carbon::now()->toDateTimeString(),
               ]);
           }
        }
    }
    //同步sip的电话号码
    public function updateSettingPhoneSip($list, $setting_id=''){
        foreach($list as $v){
            $res = self::where('phone_number',$v['sip'])->count();
            if(!$res){
                self::insert([
                    'friendly_name'=>$v['sip'],
                    'phone_number'=>$v['sip'],
                    'phone_setting_id'=>$setting_id,
                    'username' => $v['sip'],
                    'password' => $v['pass'],
                    'created_at'=>Carbon::now()->toDateTimeString(),
                    'updated_at'=>Carbon::now()->toDateTimeString(),
                ]);
            }else{
                self::where('phone_number',$v)->update([
                    'password' => $v['pass'],
                    'phone_setting_id'=>$setting_id,
                    'updated_at'=>Carbon::now()->toDateTimeString(),
                ]);
            }
        }
    }
}
